package com.jash.lifxdemo;


import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;

import com.jash.lifxdemo.databinding.FragmentContentBinding;
import com.jash.lifxdemo.entities.ContentEntity;
import com.jash.lifxdemo.entities.ContentListEntity;
import com.jash.lifxdemo.entities.Entity;
import com.jash.lifxdemo.utils.CommentRecyclerAdapter;
import com.jash.lifxdemo.utils.NetService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.header.StoreHouseHeader;
import in.srain.cube.views.ptr.indicator.PtrIndicator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * A simple {@link Fragment} subclass.
 */
public class ContentFragment extends Fragment implements Callback<Entity<ContentListEntity>>, PtrHandler {
    private static final int[] ids = {0,2,8,1,9,7,12,
    19,17,11,3,5,6,10,13,20};
    private FragmentContentBinding binding;
    private CommentRecyclerAdapter<Object> adapter;
    private NetService service;
    private ImageView image;
    private int index;
    private long startId = -1;
    private boolean loading = false;
    public static ContentFragment getInstance(int index) {
        ContentFragment fragment = new ContentFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("index", index);
        fragment.setArguments(bundle);
        return fragment;
    }

    public ContentFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return DataBindingUtil.inflate(inflater, R.layout.fragment_content, container, false).getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        binding = DataBindingUtil.getBinding(view);
        Map<Class<?>, Pair<Integer, Integer>> map = new HashMap<>();
        map.put(ContentListEntity.class, Pair.create(R.layout.header_item, BR.contentList));
        map.put(ContentEntity.class, Pair.create(R.layout.item, BR.content));
        adapter = new CommentRecyclerAdapter<>(getContext(), new ArrayList<>(), map);
        binding.contentList.setAdapter(adapter);
        service = ((BaseApplication) getContext().getApplicationContext()).getService();
        index = getArguments().getInt("index");
        service.getContentList(ids[index], index == 0, index < 5, new HashMap<String, String>())
                .enqueue(this);
//        StoreHouseHeader header = new StoreHouseHeader(getContext());
//        header.setBackgroundColor(0xff000000);
//        header.initWithString("loading...");
//        binding.ptr.addPtrUIHandler(header);
//        binding.ptr.setHeaderView(header);
        image = new ImageView(getContext());
        image.setImageResource(R.mipmap.ic_launcher);
        binding.ptr.setHeaderView(image);
        binding.ptr.setPtrHandler(this);
        binding.ptr.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                ViewCompat.setScaleX(image, 1);
                ViewCompat.setScaleY(image, 1);
                ViewCompat.setRotation(image, 0);
                ViewCompat.animate(image).cancel();
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {

            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
                ViewCompat.animate(image)
                        .rotationBy(36000)
                        .setDuration(30000)
                        .start();
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {

            }

            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                float percent = ptrIndicator.getCurrentPercent();
                percent =  Math.min(percent, 1);
                ViewCompat.setScaleX(image, percent);
                ViewCompat.setScaleY(image, percent);
            }
        });
        binding.contentList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                View item = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
                int position = recyclerView.getChildAdapterPosition(item);
                if (!loading && position > adapter.getItemCount() - 5) {
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("start_id", String.valueOf(startId));
                    loading = true;
                    service.getContentList(ids[index], false, false, hashMap)
                            .enqueue(ContentFragment.this);
                }
            }
        });
    }

    @Override
    public void onResponse(Call<Entity<ContentListEntity>> call, Response<Entity<ContentListEntity>> response) {
        if (startId == -1) {
            adapter.clear();
        }
        ContentListEntity data = response.body().getData();
        if (data.getBanners() != null) {
            adapter.add(0, data);
        }
        List<ContentEntity> contents = data.getContents();
        adapter.addAll(contents);
        startId = contents.get(contents.size() - 1).getId();
        binding.ptr.refreshComplete();
        loading = false;
    }

    @Override
    public void onFailure(Call<Entity<ContentListEntity>> call, Throwable t) {
        t.printStackTrace();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
        binding.ptr.refreshComplete();
        loading = false;
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        startId = -1;
        service.getContentList(ids[index], index == 0, index < 5, new HashMap<String, String>())
                .enqueue(this);

    }
}
